<template>
       <div class="department-wrap">
          <el-dialog 
          title="部门授权"
           :visible.sync="DepartmentDialogVisible"
           @open='sendAjax'
           :lock-scroll='false'
           top='3vh'
            >
    

            <section class="selected-down" @click='selectFlag = true'>
              <el-select v-model="defaultValue"  @change='handleSelect' placeholder="请选择">
                <el-option
                  v-for="(k,i) in res.secondDept"
                  :label="k.descrshort"
                  :value="k.setid"
                  :key='i'
                 >
                </el-option>
              </el-select>
            </section>


            <section class="tree" ref='departmentTree'>
               <div class='dialog-body'>
                 <el-tree
                  :key='new Date().getTime()'
                  :data="res.showDept"
                  show-checkbox
                  :default-expand-all='true'
                  :props="defaultProps"
                  check-strictly	
                  :render-content="renderContent"
                  @check-change	='checkChange'
                  :expand-on-click-node='false'
                  :default-checked-keys	='res.CheckDeptId'
                  node-key='deptid'
                  >
                </el-tree>
              </div> 


            </section>

             <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save">保 存</el-button>
                <el-button @click="changeVisible">取 消</el-button>
             </span>
    
        </el-dialog>
       </div>
</template>

<script>
import Vue from "vue";
import {
  Checkbox,
  CheckboxGroup,
  Button,
  Dialog,
  Tree,
  Select,
  Option,
  Notification,
  MessageBox,
  Message
} from "element-ui";

Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Button);
Vue.use(Dialog);
Vue.use(Select);
Vue.use(Option);
Vue.use(Tree);
import URL from "@/common/js/adminUrl";
export default {
  mounted () {
    Bus.$on("部门授权", data => (this.DepartmentDialogVisible = data.department));
    Bus.$on("userId", data => (this.userId = data));
  },
  data () {
    return {
      DepartmentDialogVisible: false,
      userId: "",
      res: "",
      defaultValue: '',
      defaultChecked: '',
      defaultProps: {
        children: "childList",
        label: "descr"
      },
      selectFlag: false,
      selected: 'label sele',
      noselected: 'label'
    };
  },
  methods: {

    checkChange (node, data) {

      let ref = this.$refs.departmentTree
      if (ref) {
        let id = node.deptid
        let targetA = ref.querySelector(`#a${id}`)
        let targetB = ref.querySelector(`#b${id}`)


        if (data) {
          targetA.className = this.selected
          targetB.className = this.selected
        } else {
          if (targetA.className == this.selected && targetB.className == this.noselected) {
            targetA.className = this.selected
            targetB.className = this.noselected
            return
          }
          if (targetA.className == this.noselected && targetB.className == this.selected) {
            targetA.className = this.noselected
            targetB.className = this.selected
            return
          }

          if (targetA.className == this.noselected && targetB.className == this.noselected) {
            targetA.className = this.noselected
            targetB.className = this.noselected
            return
          }
          targetA.className = this.noselected
          targetB.className = this.noselected
        }




      }

    },

    handlePersonnel (node, data) {
      let ref = this.$refs.departmentTree
      if (ref) {
        let id = data.deptid
        let target = ref.querySelector(`#a${id}`)
        target.className = target.className == this.selected ? this.noselected : this.selected
        this.guanlian(node, id)
      }
    },
    handlePay (node, data) {
      let ref = this.$refs.departmentTree
      if (ref) {
        let id = data.deptid
        let target = ref.querySelector(`#b${id}`)
        target.className = target.className == this.selected ? this.noselected : this.selected
        this.guanlian(node, id)
      }
    },
    guanlian (node, id) {

      let ref = this.$refs.departmentTree


      if (ref) {


        let targetA = ref.querySelector(`#a${id}`)
        let targetB = ref.querySelector(`#b${id}`)

        if (targetA.className == this.selected && targetB.className == this.selected) {
          node.checked = true
        } else if (targetA.className == this.noselected || targetB.className == this.noselected) {
          node.checked = false

        }
      }
    },
    renderContent (h, { node, data, store }) {
      return (
        <span style="overflow:hidden; font-size: 14px; padding-right: 8px;">
          <span>
            <span>{node.label}</span>
          </span>
          <span style='float:right;margin-right:15px'>
            <label class={data.personnel ? this.selected : this.noselected} style='margin-right:16px' id={'a' + data.deptid} data-id={'a' + data.deptid} on-click={() => this.handlePersonnel(node, data)}></label><i class='name-type1'>人事</i>   
            <label class={data.pay ? this.selected : this.noselected} style='margin-right:6px' data-id={'b' + data.deptid} id={'b' + data.deptid} on-click={() => this.handlePay(node, data)}></label><i class='name-type2'>薪酬</i>   
          </span>
        </span>)
    },
    handleSelect (val) {

      if (this.selectFlag) {
        let params = {
          userId: this.userId,
          setId: val
        }

        this.Axios
          .Post(URL.querydeptAuth.url, params)
          .then((res) => {
            this.res = res.data.datas

          })
      }

    },


    sendAjax () {

      this.Axios
        .Post(URL.deptAuth.url + "?userId=" + this.userId)
        .then(res => {
          this.res = res.data.datas;
          // 根据节后台返回的setId 决定下拉菜单的默认值
          this.res.secondDept.forEach((ele, i) => {
            if (this.res.secondDept[i].setid == this.res.setId) {
              this.defaultValue = this.res.secondDept[i].setid
            }
          }, this);

        });
    },
    save () {

      MessageBox.confirm('确定保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        let ref = this.$refs.departmentTree
        let self = this
        if (ref) {
          let all = ref.querySelectorAll('.label')
          let personnelArr = []
          let payArr = []

          for (let i = 0; i < all.length; i++) {
             if (all[i].id.substring(0, 1) == 'a') {
              personnelArr.push(all[i])
            } else if (all[i].id.substring(0, 1) == 'b') {
              payArr.push(all[i])
            }
            
          }
          

          let resultArr = []

          payArr.forEach((ele, q) => {
            if (personnelArr[q].className == this.selected || payArr[q].className == this.selected) {
              resultArr.push({
                deptId: payArr[q].id.substring(1),
                personnel: (function () {
                  if (personnelArr[q].className == self.selected) {
                    return 1
                  } else {
                    return 0
                  }
                }()),
                pay: (function () {
                  if (payArr[q].className == self.selected) {
                    return 1
                  } else {
                    return 0
                  }
                }())

              })
            }
          })


          let params = {
            userId: this.userId,
            setId: this.defaultValue,
            userDepts: resultArr
          }

          this.Axios
            .Post(URL.saveDeptAuth.url, params)
            .then((res) => {
              if (res.data.status == 1) {
                Notification({
                  title: '保存成功',
                  type: 'success',
                  offset: '1'
                })
              } else {
                Notification({
                  title: '保存失败',
                  type: 'error',
                  offset: '1'
                })
              }
            })

          this.changeVisible()

        }
      }).catch(() => {


      });

    },
    changeVisible () {

      this.DepartmentDialogVisible = false;

    }
  }
};
</script>

<style lang='less'>


::-webkit-scrollbar {
  width: 0px;
}
.department-wrap {

  .dialog-body {
    max-height:360px;
    overflow:auto;
  .el-tree {
    border:0;
  }
  .name-type1,
  .name-type2 {
    font-style:normal;
    position:relative;
    top:-4px;
  }

  .name-type1 {
    left:-9px;
  }
   .name-type2 {
    left:2px;
  }
}

  .checkbox-group {
    padding: 40px 0 0 40px;
  }
  .checkbox-group div {
    margin-bottom: 10px;
  }
  .selected-down {
    margin-bottom: 12px;
  }

  .label {
    display: inline-block;
    position: relative;
    top: 4px;
    border: 1px solid #bfcbd9;
    border-radius: 4px;
    box-sizing: border-box;
    width: 18px;
    height: 18px;
    background-color: #fff;
    z-index: 1;
    cursor: pointer;
    transition: border-color 0.25s cubic-bezier(0.71, -0.46, 0.29, 1.46),
      background-color 0.25s cubic-bezier(0.71, -0.46, 0.29, 1.46);
  }

  .sele {
    background-color: #20a0ff;
    border-color: #0190fe;
  }

  .sele::after {
    content: "\2714";
    color: #fff;
    position: absolute;
    left: 3px;
    top: -10px;
  }
}
</style>